"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 极致RTO-硬件故障类
Case Name   : 开启极致RTO，业务压力后备机进行build过程中，注入主机磁盘满故障
Create At   : 2020/10/15
Owner       : @peilinqian
Description :
    1、开启极致RTO
    2、备机进行重建
    3、注入磁盘满故障
    4、等待10S，恢复主机故障
    5、重启集群
    6、查询主备状态
    7、备机进行重建
    8、查询主备状态
    9、执行完成后，关闭极致RTO
    10、查询主备数据是否一致
Expect      :
    1、开启极致RTO成功
    2、备机开始进行重建
    3、注入磁盘满故障成功
    4、等待10S，恢复主机故障成功
    5、重启集群完成
    6、查询主备状态，主机正常，备机1stop
    7、备机进行重建成功
    8、查询主备状态正常
    9、执行完成后，关闭极致RTO成功
    10、查询主备数据一致
History     :
    modified：2021-4-22 by 5328113;状态结果查询方式变更，修改脚本；
    modified：2021-3-9 by 5328113;主备同步方法调用修改，增加超时等待时间；减少build注入故障等待时长；
    modified：2021-2-5 by 5328113;guc参数还原时指定还原值
    Modified: 2020/1/12  modified by @peilinqian，build成功后，查询主备状态，
        备机可能Standby Need repair(Connecting)，需要增加等待主备同步
    modified:2021-1-28 by 5328113;删除start成功断言，删除不必要tpcc
"""

import time
import unittest

from testcase.utils.ComThread import ComThread
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class ExtremeRto(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(
            '----Opengauss_Reliability_RTO_Hardware_Disk_Case006:初始化----')

        self.pri_root = Node(node='PrimaryRoot')
        self.pri_dbuser = Node(node='PrimaryDbUser')
        self.sta1_root = Node(node='Standby1Root')
        self.sta1_dbuser = Node(node='Standby1DbUser')
        self.sta2_dbuser = Node(node='Standby2DbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.sta_1_sh = CommonSH('Standby1DbUser')
        self.sta_2_sh = CommonSH('Standby2DbUser')
        self.com = Common()
        self.constant = Constant()
        self.tpcc_path = macro.TPCC_PATH
        self.node_num = self.com.get_node_num(self.pri_root)
        self.log.info(self.node_num)
        self.max_time = 1200
        self.min_time = 300

    def test_main(self):
        try:
            self.log.info('----1、开启极致RTO----')
            msg = self.pri_sh.executeGsguc('set',
                                           self.constant.GSGUC_SUCCESS_MSG,
                                           'replication_type=1')
            self.assertTrue(msg)
            msg = self.pri_sh.executeGsguc('set',
                                           self.constant.GSGUC_SUCCESS_MSG,
                                           'recovery_parse_workers=4')
            self.assertTrue(msg)
            msg = self.pri_sh.executeGsguc('set',
                                           self.constant.GSGUC_SUCCESS_MSG,
                                           'recovery_redo_workers=4')
            self.assertTrue(msg)
            msg = self.pri_sh.executeGsguc('set',
                                           self.constant.GSGUC_SUCCESS_MSG,
                                           'hot_standby=off')
            self.assertTrue(msg)
            # 重启数据库配置文件生效
            self.pri_sh.stopDbCluster()
            time.sleep(2)
            self.pri_sh.startDbCluster()

            self.log.info('----查看主机query，同步是否正常----')
            self.pri_sh.check_location_consistency('primary',
                                                   self.node_num,
                                                   self.min_time)
            self.log.info('----查询主备状态----')
            status = self.pri_sh.getDbClusterStatus('status')
            self.assertTrue(status)

            self.log.info('----备机数据库进行gs_ctl stop；----')
            stop_msg = self.sta_1_sh.stopDbInstance()
            self.assertIn(self.constant.GS_CTL_STOP_SUCCESS_MSG, stop_msg)

            self.log.info('----主机执行TPCC----')
            tpcc_cmd = f'. runBenchmark.sh {macro.TPCC_PROPS_FILENAME}'
            tpcc_result = self.com.startTPCC(self.pri_root,
                                             self.tpcc_path,
                                             tpcc_cmd)
            self.log.info(tpcc_result)
            error_flags = ('error', 'ERROR', 'FATAL')
            if self.constant.TPCC_SUCCESS_MSG in tpcc_result:
                self.assertFalse(
                    any(err in tpcc_result for err in error_flags))
            else:
                self.assertTrue(False)

            self.log.info('----等待主机及备2同步----')
            self.pri_sh.check_location_consistency('primary',
                                                   self.node_num - 1,
                                                   self.min_time)

            self.log.info('----2、备机进行重建----')
            build_thread = ComThread(self.sta_1_sh.executeGsctl, args=(
                'build', self.constant.REBUILD_SUCCESS_MSG,))
            build_thread.setDaemon(True)
            build_thread.start()
            time.sleep(2)

            self.log.info('----3、注入磁盘满故障----')
            self.log.info("-----------获取主机磁盘信息 -----------")
            df_cmd = f"df -h {macro.DB_INSTANCE_PATH}"
            self.log.info(df_cmd)
            df_result = self.pri_root.sh(df_cmd).result()
            self.log.info(df_result)
            self.DISK_NAME = df_result.splitlines()[-1].split()[0].strip()

            self.log.info("-----------注入磁盘满故障 -----------")
            inject_cmd = f'rfile_full (diskname) values ({self.DISK_NAME})'
            inject_result = self.com.cfe_inject(self.pri_root, inject_cmd)
            self.log.info(inject_result)
            success_msg = self.constant.CFE_DISK_FULL_SUCCESS_MSG
            self.assertIn(success_msg, inject_result)

            self.log.info("-----------获取主机磁盘占用情况 -----------")
            df_cmd = f"df -h {macro.DB_INSTANCE_PATH}"
            self.log.info(df_cmd)
            df_result = self.pri_root.sh(df_cmd).result()
            self.log.info(df_result)
            self.USED_PERCENT = df_result.splitlines()[-1].split()[4].strip()
            self.assertTrue(self.USED_PERCENT == '100%')

            # 等待build重建完成
            build_thread.join()
            build_result = build_thread.get_result()
            self.log.info(build_result)
            self.log.info('----查询主备状态----')
            self.sta_1_sh.getDbClusterStatus('status')

            self.log.info('----4、等待10S，恢复主机故障----')
            self.log.info("-----------清除磁盘满故障 -----------")
            clean_cmd = f'rfile_full where(diskname={self.DISK_NAME})'
            clean_result = self.com.cfe_clean(self.pri_root, clean_cmd)
            self.log.info(clean_result)
            self.assertIn(self.constant.CFE_DISK_CLEAN_SUCCESS_MSG,
                          clean_result)
            self.log.info("-----------获取主机磁盘占用情况 -----------")
            df_cmd = f"df -h {macro.DB_INSTANCE_PATH}"
            self.log.info(df_cmd)
            df_result = self.pri_root.sh(df_cmd).result()
            self.log.info(df_result)
            self.USED_PERCENT = df_result.splitlines()[-1].split()[4].strip()
            self.assertTrue(self.USED_PERCENT != '100%')

            self.log.info('----5、重启集群-----')
            self.pri_sh.startDbCluster()

            self.log.info('----6、查询主备状态-----')
            status_msg = self.pri_sh.getDbClusterStatus('detail')
            self.log.info(status_msg)

            if not build_result:
                self.log.info('----7、备机再次进行重建-----')
                rebuild_result = self.sta_1_sh.build_fail_scp_crtfile()
                if rebuild_result:
                    self.log.info('再次进行备机重建成功，已恢复')
                else:
                    self.log.info('再次进行备机重建失败，请检查失败原因')
                self.assertTrue(rebuild_result)

            self.log.info('----查看主机query，同步是否正常-----')
            self.pri_sh.check_location_consistency('primary',
                                                   self.node_num,
                                                   self.min_time)
            self.log.info('----8、查询主备状态----')
            status = self.pri_sh.getDbClusterStatus('status')
            self.assertTrue(status)

        finally:
            self.log.info('----9、执行完成后，关闭极致RTO-----')
            msg = self.pri_sh.executeGsguc('set',
                                           self.constant.GSGUC_SUCCESS_MSG,
                                           'recovery_parse_workers = 1')
            self.assertTrue(msg)
            msg = self.pri_sh.executeGsguc('set',
                                           self.constant.GSGUC_SUCCESS_MSG,
                                           'recovery_redo_workers = 1')
            self.assertTrue(msg)
            msg = self.pri_sh.executeGsguc('set',
                                           self.constant.GSGUC_SUCCESS_MSG,
                                           'hot_standby=on')
            self.assertTrue(msg)
            # 重启数据库配置文件生效
            self.pri_sh.stopDbCluster()
            time.sleep(2)
            self.pri_sh.startDbCluster()

            # 校验备机是否完成数据同步
            self.log.info('校验备机是否完成数据同步')
            flag_1 = self.sta_1_sh.check_location_consistency('standby',
                                                              self.node_num,
                                                              self.min_time)
            self.assertTrue(flag_1)
            flag_2 = self.sta_2_sh.check_location_consistency('standby',
                                                              self.node_num,
                                                              self.min_time)
            self.assertTrue(flag_2)

            self.log.info('----10、查询主备数据是否一致-----')
            nodes_tuple = (self.pri_dbuser,
                           self.sta1_dbuser,
                           self.sta2_dbuser)
            flag = self.com.check_data_sample_by_all(r'\d', *nodes_tuple)
            self.assertTrue(flag)

            table_dict = self.com.format_sql_result(
                self.pri_sh.executDbSql(r'\d'))
            table_name = table_dict.get('Name')
            for name in table_name:
                select_sql = f'select count(*) from {name};'
                flag = self.com.check_data_sample_by_all(select_sql,
                                                         *nodes_tuple)
                self.assertTrue(flag)

    def tearDown(self):
        df_cmd = f"df -h {macro.DB_INSTANCE_PATH}"
        self.log.info(df_cmd)
        df_result = self.pri_root.sh(df_cmd).result()
        self.log.info(df_result)
        self.USED_PERCENT = df_result.splitlines()[-1].split()[4].strip()
        if self.USED_PERCENT == '100%':
            self.log.info('----异常中断，磁盘故障未恢复处理----')
            clean_disk_cmd = f'rfile_full  where(diskname={self.DISK_NAME})'
            clean_disk_result = self.com.cfe_clean(self.pri_root,
                                                   clean_disk_cmd)
            self.log.info(clean_disk_result)

        self.log.info('----校验刷脏页是否完成-----')
        self.pri_sh.check_whether_remain_dirty_page()

        self.log.info(
            '----Opengauss_Reliability_RTO_Hardware_Disk_Case006:结束----')
